package club.dmyang.service;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.exception.HyBlogException;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.dao.CategoryMapper;
import club.dmyang.entity.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by brss on 2018/7/14.
 */
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleService articleService;

    @Override
    public boolean addOneCategory(Category category) {
        try{
            categoryMapper.insertSelective(category);
        }
        catch(Exception e){
            LOGGER.error("添加分类失败："+e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public Category findOneById(Integer cid) {
        Category category = categoryMapper.selectByPrimaryKey(cid);
        return category;
    }

    /**
     * limit
     * @param page
     * @param limit 每页的容量
     * @return
     * start = (page-1)*limit
     * 每页容量=limit
     */
    @Override
    public List<Category> findByPageAndLimit(Integer page, Integer limit) {
        if ( page < 1 || limit < 1 ){
            LOGGER.error("page或limit错误！[ page = "+page + "limit = "+limit + "]");
            throw new HyBlogException(RespCodeEnums.GLOBAL_CODE_PARAMETER_ERROR);
        }
        List<Category> categories = categoryMapper.selectByPageAndLimit((page - 1) * limit, limit);
        return categories;
    }

    /**
     * 修改一条分类信息
     *
     * @param category
     * @return
     */
    @Override
    public boolean updateOneCategory(Category category) {

        int num = categoryMapper.updateByPrimaryKey(category);
        if (num<1){
            LOGGER.error("修改分类信息失败:" + category);
            return false;
        }
        return true;
    }

    /**
     * 删除主键为cid的分类（保证该分类下没有文章）
     *
     * @param cid
     * @return
     */
    @Override
    public boolean deleteOneCategory(Integer cid) {
        //查询有无文章的category_id = 传入的cid
        Integer num = articleService.findNumByCategoryId(cid);
        if (num > 0) {
            return false;
        }
        int i = categoryMapper.deleteByPrimaryKey(cid);
        if (i > 0)
            return true;
        return false;
    }

    /**
     * 查找所有分类
     *
     * @return
     */
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    /**
     * 查询所有分类记录的个数
     * （用于分页计算页数 ）
     *
     * @return
     */
    @Override
    public int findtAllNums() {
        return categoryMapper.selectAllNums();
    }


}
